<template>
  <button
    class="text-sm text-center rounded duration-150 flex justify-center items-center"
    :class="[
      typeEnum[type],
      sizeEnum[sizeKey].button,
      { 'active:scale-105': isActiveAnim }
    ]"
    @click.stop="onBtnClick"
  >
    <!-- loading -->
    <z-svg-icon
      class="w-2 h-2 animate-spin mr-1"
      name="loading"
      color="#707070"
      v-if="loading"
    />
    <!-- icon -->
    <z-svg-icon
      v-if="icon"
      :name="icon"
      class="m-auto"
      :class="sizeEnum[sizeKey].icon"
      :color="iconColor"
      :fillClass="iconClass"
    />
    <!-- text -->
    <slot v-else />
  </button>
</template>

<script>
const EMITS_CLICK = 'click'
const typeEnum = {
  primary:
    'text-white bg-zinc-800 dark:bg-zinc-900 hover:bg-zinc-900 dark:hover:bg-zinc-700 active:bg-zinc-800 dark:active:bg-zinc-700',
  main: 'text-white bg-main dark:bg-zinc-900 hover:bg-main dark:hover:bg-zinc-700 active:bg-main dark:active:bg-zinc-700',
  info: 'text-zinc-800 dark:text-zinc-300 bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600 active:bg-zinc-200 dark:active:bg-zinc-700'
}
const sizeEnum = {
  default: {
    button: 'w-8 h-4 text-base',
    icon: ''
  },
  'icon-default': {
    button: 'w-4 h-4',
    icon: 'w-1.5 h-1.5'
  },
  small: {
    button: 'w-7 h-3 text-base',
    icon: ''
  },
  'icon-small': {
    button: 'w-3 h-3',
    icon: 'w-1.5 h-1.5'
  }
}
</script>
<script setup>
import { computed } from 'vue'
import zSvgIcon from '../svg-icon/index.vue'

/**
 * @description: 按钮组件
 * 1. 按钮类型 type 和 size 大小可选项
 * 2. 通过 props 控制按钮
 * 3. 区分icon和text按钮
 * 4. 依据当前数据状态，控制按钮样式
 * 5. 按钮点击事件
 */
const props = defineProps({
  icon: {
    type: String,
    default: ''
  },
  iconColor: {
    type: String,
    default: ''
  },
  iconClass: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'main',
    validator: (value) => {
      const keys = Object.keys(typeEnum)
      const result = keys.includes(value)
      if (!result) {
        throw new Error(`type属性值必须是${keys.join('|')}`)
      }
      return result
    }
  },
  size: {
    type: String,
    default: 'default',
    validator: (value) => {
      const keys = Object.keys(sizeEnum).filter((key) => !key.includes('icon'))
      const result = keys.includes(value)
      if (!result) {
        throw new Error(`size属性值必须是${keys.join('|')}`)
      }
      return result
    }
  },
  // 是否需要动画
  isActiveAnim: {
    type: Boolean,
    default: true
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
})

const sizeKey = computed(() => {
  return props.icon ? `icon-${props.size}` : props.size
})
const emit = defineEmits([EMITS_CLICK])

const onBtnClick = () => {
  if (props.loading) return
  emit(EMITS_CLICK)
}
</script>

<style lang="scss" scoped></style>
